package br.com.drestranho.escola.dao;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import br.com.drestranho.escola.entity.Aluno;

@Stateless
public class AlunoDAO {
	@PersistenceContext(unitName="H6Escola")
	private EntityManager em;
	
	public void atualizar(Aluno bean){
		em.merge(bean);
	}
	
	public void remover( Aluno bean) {
		em.remove(em.merge(bean));
	}
	
	public Aluno getBean(Integer id) {
		Aluno bean = em.find(Aluno.class, id);
		return bean;
	}

	public List<Aluno> getBeans(){// Lista total
//		List<Aluno> beansList = (List<Aluno>)em.createQuery("select a from Aluno a").getResultList();
//		return beansList;
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Aluno> cq = cb.createQuery(Aluno.class);
		Root<Aluno> from = cq.from(Aluno.class);
		CriteriaQuery<Aluno> select = cq.select(from);
		List<Aluno> alunos = em.createQuery(select).getResultList();
		return alunos;
	}
	
	public List<Aluno> pesqBeanNome(String nomePesq) {// Pesquisa por nome (case sensitive) com operador like
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Aluno> cq = cb.createQuery(Aluno.class);
		Root<Aluno> from = cq.from(Aluno.class);
		CriteriaQuery<Aluno> select = cq.select(from).where(cb.like(from.<String>get("nome"), "%"+nomePesq+"%"));
		List<Aluno> funcs = em.createQuery(select).getResultList();
		return funcs;
	}
	
	public void salvar(Aluno bean) {
		em.persist(bean);
	}
	
}
